const express = require("express")
const User = require('../mod/user')
const retrieve = express.Router() //创建路由

const Mail = require("../tool/mail.js")

var {
    setCrypto
} = require('../tool/crypto.js')
const Rank = require("../mod/rank")


//找回密码
retrieve.post("/", async (req, res) => {
    //需要参数 邮箱、验证码，两次密码，重设的username
    let {
        email,
        yzmval,
        password,
        checkPass,
        username
    } = req.body

    //检查密码是否一致
    if (password !== checkPass) {
        return res.json({
            message: "两次密码不一致",
            code: 201
        })
    }


    //对密码加密
    password = setCrypto(password)

    //检查该邮箱是否被注册过
    let data = await User.findOne({
        email
    })
    if (!data) {
        return res.json({
            message: "该用户不存在，请重新检查邮箱是否正确",
            code: 201
        })
    }


    //检查验证码
    let obj = JSON.parse(process.env.code)
    let time1 = Date.now()
    if (yzmval != obj.code1) {
        return res.json({
            message: "验证码错误",
            code: 202
        })
    }



    if (time1 - obj.time >= 1000 * 60 * 5) {
        return res.json({
            message: "验证码有效时间5min,现已经失效,请重新获取",
            code: 201
        })
    }


    //验证都通过，开始注册
    let datalist = await User.update({
        email
    }, {
        email,
        username,
        password
    })

    let userData = await User.findOne({
        email
    })
    if (!userData) {
        return res.status(206).json({
            message: "请重试",
            code: 201
        })
    }
    let user_id = userData._id

    if (datalist) {
        //修改成功后，需要将所有与他username相关的重置
        //1.将上传的成绩 username 重置
        let data1 = await Rank.updateMany({
            user_id
        }, {
            username
        })
        if (data1) {
            return res.json({
                datalist,
                message: "重置用户信息成功",
                code: 200
            })
        }
    }

    res.status(205).json({
        message: "注册失败，请重试",
        code: 201
    })
})


module.exports = retrieve